
// DOM 元素
// DOM 元素
const userIdInput = document.getElementById('userIdInput');
const getCartBtn = document.getElementById('getCartBtn');
const searchInput = document.getElementById('searchInput');
const searchBtn = document.getElementById('searchBtn');
const cartContainer = document.getElementById('cartContainer');
const currentUserId = document.getElementById('currentUserId');


// 获取购物车数据
getCartBtn.addEventListener('click', () => {
    const userId = userIdInput.value.trim();
    const productName = searchInput.value.trim();

    if (!userId) {
        alert('请输入用户 ID');
        return;
    }

    // 先设置用户ID到Session
    fetch('/api/cart/setUserId', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `userId=${userId}`
    })
        .then(response => {
            if (!response.ok) {
                throw new Error('设置用户ID失败');
            }
            // 设置成功后再获取购物车数据
            getCartData(userId, productName);
        })
        .catch(error => showError(error));
});

// 搜索按钮事件
searchBtn.addEventListener('click', () => {
    const userId = userIdInput.value.trim();
    const productName = searchInput.value.trim();

    if (!userId) {
        alert('请输入用户 ID');
        return;
    }

    // 先设置用户ID到Session
    fetch('/api/cart/setUserId', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `userId=${userId}`
    })
        .then(response => {
            if (!response.ok) {
                throw new Error('设置用户ID失败');
            }
            // 设置成功后再获取购物车数据
            getCartData(userId, productName);
        })
        .catch(error => showError(error));
});

// 获取购物车数据函数
function getCartData(userId, productName = '') {
    // 显示加载状态
    cartContainer.innerHTML = `
        <div class="loading">
          <i class="fas fa-spinner fa-spin"></i>
          <p>正在加载购物车数据...</p>
        </div>
    `;

    currentUserId.textContent = userId;

    // 关键修改：使用正确的API端点进行搜索
    const url = productName
        ? `/api/cart/selectCart?userId=${userId}&productName=${encodeURIComponent(productName)}`
        : `/api/cart/cartProductsList?userId=${userId}`;

    fetch(url)
        .then(response => {
            if (!response.ok) {
                throw new Error('无法加载购物车数据');
            }
            return response.json();
        })
        .then(data => {
            // 根据不同的API端点返回的数据结构进行处理
            if (productName) {
                // selectCart返回的是CartItemDTO列表，需要转换为CartProductDTO格式
                renderCartItems(convertToCartProductDTO(data));
            } else {
                // cartProductsList返回的是CartProductDTO列表
                renderCartItems(data);
            }
        })
        .catch(error => showError(error));
}

// 将CartItemDTO转换为CartProductDTO格式
function convertToCartProductDTO(cartItems) {
    return cartItems.map(item => {
        return {
            cartId: item.cartId,
            quantity: item.quantity,
            product: {
                id: item.productId,
                name: item.productName,
                price: item.price.toString(), // 转换为字符串以保持一致性
                mainImage: item.mainImage,
                // 其他字段根据需要添加或留空
            }
        };
    });
}

// 渲染购物车数据
function renderCartItems(cartItems) {
    if (!cartItems || cartItems.length === 0) {
        cartContainer.innerHTML = `
            <div class="empty-cart">
                <i class="fas fa-shopping-cart"></i>
                <h2>购物车为空</h2>
                <p>没有找到符合条件的商品</p>
            </div>
        `;
        return;
    }

    // 计算总价和商品总数
    let totalPrice = 0;
    let totalItems = 0;

    const itemsHtml = cartItems.map(item => {
        // 确保价格是数字类型
        const price = parseFloat(item.product.price);
        const itemTotal = price * item.quantity;
        totalPrice += itemTotal;
        totalItems += item.quantity;

        // 处理图片URL
        const imageUrl = item.product.mainImage
            ? item.product.mainImage.replace('./', '/')
            : 'https://via.placeholder.com/300';

        return `
         <div class="cart-item" data-price="${price}" data-quantity="${item.quantity}">
            <!-- 添加复选框 -->
            <div class="item-checkbox" style="display:none;">
                <input type="checkbox" class="cart-item-checkbox" data-cart-id="${item.cartId}">
            </div>
            <div class="item-image">
                <img src="${imageUrl}" alt="${item.product.name}">
            </div>
            <div class="item-details">
                <h3 class="item-name">${item.product.name}</h3>

                <div class="item-info">
                    <span class="item-label">单价：</span>
                    <span class="item-price">¥${price.toFixed(2)}</span>
                </div>

                <div class="item-quantity">
                    <div class="quantity-btn minus-btn" data-cart-id="${item.cartId}">
                        <i class="fas fa-minus"></i>
                    </div>
                    <span class="quantity-value">${item.quantity}</span>
                    <div class="quantity-btn plus-btn" data-cart-id="${item.cartId}">
                        <i class="fas fa-plus"></i>
                    </div>
                </div>

                <div class="item-info">
                    <span class="item-label">小计：</span>
                    <span class="item-subtotal">¥${itemTotal.toFixed(2)}</span>
                </div>

                <div class="item-actions">
                    <button class="action-btn btn-danger" data-cart-id="${item.cartId}">
                        <i class="fas fa-trash"></i> 删除
                    </button>
                </div>
            </div>
        </div>
        `;
    }).join('');

    // 修改：将清空购物车按钮移动到商品列表上方
    cartContainer.innerHTML = `
        <div class="cart-actions">
            <button class="btn-danger" id="clearCartBtn">
                <i class="fas fa-broom"></i> 清空购物车
            </button>
            
            
               <!-- 添加多选按钮 -->
            <button class="btn-multi-select" id="multiSelectBtn">
                <i class="fas fa-check-square"></i> 多选
            </button>
            
            <!-- 多选模式下的操作按钮 -->
            <div class="multi-select-actions" id="multiSelectActions" style="display:none;">
                <button class="btn-select-all" id="selectAllBtn">
                    <i class="fas fa-check-double"></i> <span id="selectAllText">全选</span>
                </button>
                <button class="btn-cancel" id="cancelMultiSelectBtn">
                    <i class="fas fa-times"></i> 取消
                </button>
                <button class="btn-checkout-selected" id="checkoutSelectedBtn">
                    <i class="fas fa-cash-register"></i> 结算选中
                </button>
            </div>
            
            
            
        </div>
        
        <div class="cart-items">
            ${itemsHtml}
        </div>

        <div class="summary">
            <div class="total-items">
                <i class="fas fa-box"></i> 商品总数: ${totalItems} 件
            </div>
            <div class="total-price">
                <i class="fas fa-receipt"></i> 总金额: ¥${totalPrice.toFixed(2)}
            </div>
            <!-- 修改：在原来的位置添加结算按钮 -->
            <button class="btn-primary" id="checkoutBtn" style="color: #c0392b">
                <i class="fas fa-cash-register"></i> 结算商品
            </button>
        </div>
    `;



    // 添加多选按钮事件
    document.getElementById('multiSelectBtn').addEventListener('click', enterMultiSelectMode);
    document.getElementById('cancelMultiSelectBtn').addEventListener('click', exitMultiSelectMode);
    document.getElementById('selectAllBtn').addEventListener('click', toggleSelectAll);
    document.getElementById('checkoutSelectedBtn').addEventListener('click', function() {
        const userId = userIdInput.value.trim();
        checkoutSelectedItems(userId);
    });








    // 添加删除按钮事件
    document.querySelectorAll('.btn-danger[data-cart-id]').forEach(btn => {
        btn.addEventListener('click', function() {
            const cartId = this.getAttribute('data-cart-id');
            const userId = userIdInput.value.trim();

            if (confirm('确定要删除这个商品吗？')) {
                // 发送删除请求
                fetch(`/api/cart/delete/${cartId}?userId=${userId}`, { method: 'DELETE' })
                    .then(response => {
                        if (response.ok) {
                            // 重新加载购物车
                            getCartData(userId, searchInput.value.trim());
                        } else {
                            alert('删除失败');
                        }
                    })
                    .catch(error => alert('删除失败: ' + error.message));
            }
        });
    });

    // 添加清空购物车按钮事件
    document.getElementById('clearCartBtn').addEventListener('click', function() {
        const userId = userIdInput.value.trim();

        if (confirm('确定要清空整个购物车吗？此操作不可撤销！')) {
            // 发送清空购物车请求
            fetch(`/api/cart/clearCart?userId=${userId}`, { method: 'DELETE' })
                .then(response => {
                    if (response.ok) {
                        // 重新加载购物车
                        getCartData(userId);
                    } else {
                        alert('清空失败');
                    }
                })
                .catch(error => alert('清空失败: ' + error.message));
        }
    });




    // 在renderCartItems函数中修改结算按钮事件
    document.getElementById('checkoutBtn').addEventListener('click', function() {
        const userId = userIdInput.value.trim();
        if (cartItems.length === 0) {
            alert('购物车为空，无法结算');
            return;
        }

        // 存储要结算的商品ID
        const cartItemIds = cartItems.map(item => item.cartId);
        sessionStorage.setItem('checkoutItems', JSON.stringify(cartItemIds));
        sessionStorage.setItem('userId', userId);

        // 跳转到结算页面
        window.location.href = 'checkout.html';
    });
    // // 添加结算按钮事件
    // document.getElementById('checkoutBtn').addEventListener('click', function() {
    //     const userId = userIdInput.value.trim();
    //     if (cartItems.length === 0) {
    //         alert('购物车为空，无法结算');
    //         return;
    //     }
    //
    //     alert(`用户 ${userId} 的购物车商品结算中...`);
    //     // 这里可以添加实际的结算逻辑
    //     // 例如：fetch('/api/checkout', { method: 'POST', body: JSON.stringify({ userId }) })
    // });

    // 添加数量按钮事件
    document.querySelectorAll('.minus-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const cartId = this.getAttribute('data-cart-id');
            const userId = userIdInput.value.trim();
            const quantitySpan = this.nextElementSibling;
            const currentQuantity = parseInt(quantitySpan.textContent);

            updateQuantity(cartId, userId, currentQuantity - 1, quantitySpan);
        });
    });

    document.querySelectorAll('.plus-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const cartId = this.getAttribute('data-cart-id');
            const userId = userIdInput.value.trim();
            const quantitySpan = this.previousElementSibling;
            const currentQuantity = parseInt(quantitySpan.textContent);

            updateQuantity(cartId, userId, currentQuantity + 1, quantitySpan);
        });
    });
}


// 定义updateTotalPrice函数
function updateTotalPrice() {
    let totalPrice = 0;
    let totalItems = 0;

    document.querySelectorAll('.cart-item').forEach(item => {
        const quantity = parseInt(item.dataset.quantity);
        const price = parseFloat(item.dataset.price);

        totalItems += quantity;
        totalPrice += price * quantity;
    });

    // 更新总价显示
    const totalItemsElement = document.querySelector('.total-items');
    const totalPriceElement = document.querySelector('.total-price');

    if (totalItemsElement && totalPriceElement) {
        totalItemsElement.innerHTML = `<i class="fas fa-box"></i> 商品总数: ${totalItems} 件`;
        totalPriceElement.innerHTML = `<i class="fas fa-receipt"></i> 总金额: ¥${totalPrice.toFixed(2)}`;
    }
}





// 更新商品数量函数--无刷新更新
function updateQuantity(cartId, userId, newQuantity, quantitySpan) {
    // 检查新数量是否有效
    if (newQuantity < 0) {
        alert('数量不能为负数');
        return;
    }

    // 如果数量为0，询问是否删除
    if (newQuantity === 0) {
        if (confirm('数量将减少为0，是否删除该商品？')) {
            // 发送删除请求
            fetch(`/api/cart/delete/${cartId}?userId=${userId}`, { method: 'DELETE' })
                .then(response => {
                    if (response.ok) {
                        getCartData(userId, searchInput.value.trim());
                    } else {
                        console.error('删除失败');
                    }
                });
        }
        return;
    }

    // 显示加载状态
    const originalQuantity = quantitySpan.textContent;
    quantitySpan.innerHTML = `<i class="fas fa-spinner fa-spin"></i>`;

    // 发送更新请求
    fetch(`/api/cart/updateQuantity?cartId=${cartId}&userId=${userId}&quantity=${newQuantity}`, {
        method: 'PUT'
    })
        .then(response => {
            if (!response.ok) {
                throw new Error('更新数量失败');
            }
            return response.json();
        })
        .then(updatedCart => {
            // 更新成功后，直接更新显示的数值
            quantitySpan.textContent = updatedCart.quantity;

            // 更新DOM中的data-quantity属性
            const cartItem = quantitySpan.closest('.cart-item');
            cartItem.dataset.quantity = updatedCart.quantity;

            // 更新小计
            const price = parseFloat(cartItem.dataset.price);
            const subtotal = price * updatedCart.quantity;
            cartItem.querySelector('.item-subtotal').textContent = `¥${subtotal.toFixed(2)}`;

            // 更新总价
            updateTotalPrice();
        })
        .catch(error => {
            console.error('更新数量失败:', error);
            // 恢复原来的数量
            quantitySpan.textContent = originalQuantity;
        });
}



// 更新选中商品的总价函数
function updateSelectedTotal() {
    let selectedTotalPrice = 0;
    let selectedTotalItems = 0;

    document.querySelectorAll('.cart-item-checkbox:checked').forEach(checkbox => {
        const cartItem = checkbox.closest('.cart-item');
        const price = parseFloat(cartItem.dataset.price);
        const quantity = parseInt(cartItem.querySelector('.quantity-value').textContent);
        const subtotal = price * quantity;

        selectedTotalPrice += subtotal;
        selectedTotalItems += quantity;

        // 更新小计显示
        cartItem.querySelector('.item-subtotal').textContent = `¥${subtotal.toFixed(2)}`;
    });

    // 更新总价显示
    const totalItemsElement = document.querySelector('.total-items');
    const totalPriceElement = document.querySelector('.total-price');

    if (totalItemsElement && totalPriceElement) {
        totalItemsElement.innerHTML = `<i class="fas fa-box"></i> 商品总数: ${selectedTotalItems} 件`;
        totalPriceElement.innerHTML = `<i class="fas fa-receipt"></i> 总金额: ¥${selectedTotalPrice.toFixed(2)}`;
    }
}




// 添加数量按钮事件监听
function setupQuantityButtons() {
    document.querySelectorAll('.minus-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const cartId = this.getAttribute('data-cart-id');
            const userId = userIdInput.value.trim();
            const quantitySpan = this.nextElementSibling;
            const currentQuantity = parseInt(quantitySpan.textContent);

            updateQuantity(cartId, userId, currentQuantity - 1, quantitySpan);
        });
    });

    document.querySelectorAll('.plus-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const cartId = this.getAttribute('data-cart-id');
            const userId = userIdInput.value.trim();
            const quantitySpan = this.previousElementSibling;
            const currentQuantity = parseInt(quantitySpan.textContent);

            updateQuantity(cartId, userId, currentQuantity + 1, quantitySpan);
        });
    });
}



// 显示错误
function showError(error) {
    cartContainer.innerHTML = `
    <div class="empty-cart">
      <i class="fas fa-exclamation-triangle"></i>
      <h2>加载失败</h2>
      <p>${error.message || '无法加载购物车数据'}</p>
      <button class="action-btn" style="margin-top: 20px;" onclick="location.reload()">
        <i class="fas fa-sync"></i> 重新加载
      </button>
    </div>
    `;
}

// 页面加载时设置示例用户 ID
window.addEventListener('DOMContentLoaded', () => {
    userIdInput.value = '1001';
    // 自动加载示例用户的购物车
    getCartBtn.click();
});

















